package scau.redi.social_platform.controller.user;


import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import scau.redi.social_platform.common.exception.AuthException;
import scau.redi.social_platform.common.staticCode.Const;
import scau.redi.social_platform.common.staticCode.ResponseCode;
import scau.redi.social_platform.common.util.ResponsePageUtil;
import scau.redi.social_platform.common.util.ResponseUtil;
import scau.redi.social_platform.common.util.SessionContextUtil;
import scau.redi.social_platform.domain.pojo.*;
import scau.redi.social_platform.service.SharedCommentService;
import scau.redi.social_platform.service.SharedService;
import scau.redi.social_platform.service.UserService;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author redi
 * @since 2022-05-05
 */

@RestController
@Api(value = "user",description = "用户操作")
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    SharedCommentService sharedCommentService;
    @Autowired
    SharedService sharedService;
    // 创建实例
    SessionContextUtil sessionUtil = SessionContextUtil.getInstance();

    @GetMapping("/collectShared.do")
    @ApiOperation("收藏分享（普通用户、管理员）")
    public Map<String, Object> collectShared(@RequestParam(value = "sharedId", required = true)int sharedId,
                                            HttpSession session)
    {
        // 检查权限
        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        if (null == user){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
        }
        // 插入记录
        SharedCollection sharedCollection = new SharedCollection();
        sharedCollection.setCollectedUserId(user.getId());
        sharedCollection.setSharedId(sharedId);
        sharedCollection.setCreateTime(new Date());
        sharedCollection.setUpdateTime(new Date());

        int collectSharedResultCode = userService.collectShared(sharedCollection);    //返回值：插入失败则为0， 否则为插入行序号
        if (collectSharedResultCode == 0){
            return ResponseUtil.fail("shared 收藏失败");
        }
        return ResponseUtil.success("shared 收藏成功");
    }

    @GetMapping("/unCollectShared.do")
    @ApiOperation("取消收藏分享（普通用户、管理员）")
    public Map<String, Object> unCollectShared(@RequestParam(value = "sharedId", required = true)int sharedId,
                                             HttpSession session)
    {
        // 检查权限
        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        if (null == user){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
        }
        // 删除记录
        int unCollectSharedResultCode = userService.unCollectShared(sharedId,user.getId());    //返回值：插入失败则为0， 否则为插入行序号
        if (unCollectSharedResultCode == 0){
            return ResponseUtil.fail("shared 取消收藏失败");
        }
        return ResponseUtil.success("shared 取消收藏成功");
    }

    @GetMapping("/likeShared.do")
    @ApiOperation("点赞分享（普通用户、管理员）")
    public Map<String, Object> likeShared(@RequestParam(value = "sharedId", required = true)int sharedId,
                                          @RequestParam(value = "sessionId",required = true)String sessionId)
    {
        // 检查权限
        HttpSession session = sessionUtil.getSession(sessionId); //就多了这一行
        UserInfo user;
        try {
            user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        }catch (NullPointerException e){
            e.printStackTrace();
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(), ResponseCode.NEED_LOGIN.getCode());
        }
        // 点赞分享
        SharedLiked sharedLiked = new SharedLiked();
        sharedLiked.setSharedId(sharedId);
        sharedLiked.setLikedUserId(user.getId());
        sharedLiked.setCreateTime(new Date());
        sharedLiked.setUpdateTime(new Date());

        int likeSharedResultCode = userService.likeShared(sharedLiked);    //返回值：插入失败则为0， 否则为插入行序号
        if (likeSharedResultCode == 0){
            return ResponseUtil.fail("shared 点赞失败");
        }
        return ResponseUtil.success("shared 点赞成功");
    }

    @GetMapping("/unLikeShared.do")
    @ApiOperation("取消点赞分享（普通用户、管理员）")
    public Map<String, Object> unLikeShared(@RequestParam(value = "sharedId", required = true)int sharedId,
                                          HttpSession session)
    {
        // 检查权限
        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        if (null == user){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
        }
        // 删除记录
        int unLikeSharedResultCode = userService.unLikeShared(sharedId,user.getId());    //返回值：插入失败则为0， 否则为插入行序号
        if (unLikeSharedResultCode == 0){
            return ResponseUtil.fail("shared 取消点赞失败");
        }
        return ResponseUtil.success("shared 取消点赞成功");
    }

    @GetMapping("/getAllCollectShared.do")
    @ApiOperation("获取所有收藏的分享（普通用户、管理员）")
    public Object getAllCollectShared(@RequestParam(value = "page",defaultValue = "1")int page,
                                             @RequestParam(value = "size",defaultValue = "5")int size,
                                             HttpSession session)
    {
        // 检查权限
        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        if (null == user){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
        }

        ResponsePageUtil allCollectShared = userService.getAllCollectShared(user.getId(), page, size);
        if (null == allCollectShared){
            return ResponseUtil.fail("该用户所有收藏的分享 获取失败");
        }
        return ResponseUtil.success(allCollectShared);
    }

    @GetMapping("/getAllLikedShared.do")
    @ApiOperation("获取当前用户所有点赞的分享（普通用户、管理员）")
    public Object getAllLikedShared(@RequestParam(value = "page",defaultValue = "1")int page,
                                    @RequestParam(value = "size",defaultValue = "5")int size,
                                    //HttpSession session
                                    @RequestParam(value = "sessionId",required = true)String sessionId
                                    )
    {
        // 检查权限
//        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
//        if (null == user){
//            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
//        }
        // 检查权限
        HttpSession session = sessionUtil.getSession(sessionId); //就多了这一行
        try{
            UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
            ResponsePageUtil allCollectShared = userService.getAllLikedShared(user.getId(), page, size);
            if (null == allCollectShared){
                return ResponseUtil.fail("该用户所有点赞的分享 获取失败");
            }
            return ResponseUtil.success(allCollectShared);
        }catch (NullPointerException e){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(), ResponseCode.NEED_LOGIN.getCode());
        }
    }

    @GetMapping("/getAllMyShared.do")
    @ApiOperation("获取自己所有的分享（分页）（普通用户、管理员）")
    public Map<String, Object> getAllMyShared(@RequestParam(value = "page",defaultValue = "1")int page,
                                              @RequestParam(value = "size",defaultValue = "5")int size,
                                              //HttpSession session
                                              @RequestParam(value = "sessionId",required = true)String sessionId)
    {
        // 检查权限
        HttpSession session = sessionUtil.getSession(sessionId); //多了这一行

        // 逻辑
        try{
            UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
            return ResponseUtil.success(userService.getAllMyShared(user.getId(), page, size));
        }catch (NullPointerException e){
            e.printStackTrace();
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(), ResponseCode.NEED_LOGIN.getCode());
        }
    }

    @PostMapping("/commentOnShared.do")
    @ApiOperation("评论分享（普通用户、管理员）")
    public Map<String, Object> createShared(@RequestParam(value = "content", required = true)String content,
                                            @RequestParam(value = "sharedId", required = true)Integer sharedId,
                                            HttpSession session
    )
    {
        // 检查权限
        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        if (null == user){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
        }
        // 检查shared status
        Shared sharedById = sharedService.findById(sharedId);
        if (sharedById.getStatusId() != Const.SharedStatus.STATUS_NORMAL){
            return ResponseUtil.fail("该分享不可评论");
        }
        // 新建要插入的comment
        SharedComment comment = new SharedComment();
        comment.setUserId(user.getId());
        comment.setCommentText(content);
        comment.setSharedId(sharedId);
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());
        // 插入comment
        int insertResultCode = sharedCommentService.createSharedComment(comment);
        if (insertResultCode>0){
            return ResponseUtil.success(comment);
        }
        return ResponseUtil.fail("comment 插入失败！");
    }

    @GetMapping("/deleteComment.do")
    @ApiOperation("删除评论（普通用户、管理员）")
    public Map<String, Object> deleteComment(@RequestParam(value = "commentId", required = true)Integer commentId,
                                             HttpSession session
    )
    {
        // 检查权限
        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        if (null == user){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
        }

        // 删除comment
        int deleteResultCode = sharedCommentService.deleteByPrimaryKeyAndUserId(commentId,user.getId());
        if (deleteResultCode>0){
            return ResponseUtil.success("comment 删除成功！");
        }
        return ResponseUtil.fail("comment 删除失败！");
    }

    @PostMapping("/commentOnComment.do")
    @ApiOperation("评论评论（普通用户、管理员）")
    public Map<String, Object> commentOnComment(@RequestParam(value = "content", required = true)String content,
                                                @RequestParam(value = "replyCommentId", required = true)Integer replyCommentId,
                                                HttpSession session
    )
    {
        // 检查权限
        UserInfo user = (UserInfo) session.getAttribute(Const.CURRENT_USER);
        if (null == user){
            return ResponseUtil.fail(ResponseCode.NEED_LOGIN.getDesc(),ResponseCode.NEED_LOGIN.getCode());
        }

        // 找到要评论的评论的shareId
        SharedComment replyComment = sharedCommentService.findById(replyCommentId);

        // 新建评论
        SharedComment comment = new SharedComment();
        comment.setUserId(user.getId());
        comment.setCommentText(content);
        comment.setSharedId(replyComment.getSharedId());
        comment.setReplyCommentId(replyCommentId);
        comment.setCreateTime(new Date());
        comment.setUpdateTime(new Date());

        // 插入comment
        int insertResultCode = sharedCommentService.createSharedComment(comment);
        if (insertResultCode>0){
            return ResponseUtil.success(comment);
        }
        return ResponseUtil.fail("comment 插入失败！");
    }

}

